package com.gitee.ice1938.module.admin.sysoption;

import javax.cache.Caching;
import javax.sql.DataSource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.jdbc.AbstractBaseDataSourceInitializer;
import org.springframework.boot.jdbc.AbstractDataSourceInitializer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.MissingJCacheCacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.ResourceLoader;

import com.gitee.ice1938.module.admin.sysoption.fun.OptionService;

@Configuration
@ConditionalOnWebApplication
@ComponentScan("com.gitee.ice1938.module.admin.sysoption")
@EnableCaching
public class AdminSysOptionModuleConfig implements InitializingBean {

	@Autowired
	private MessageSource messageSource;

	@Autowired
	private OptionService optionService;

	@Override
	public void afterPropertiesSet() throws Exception {
		// 根据模块信息添加i18n 默认配置 MessageSourceAutoConfiguration会根据是否配置了前缀进行资源相关类加载
		ResourceBundleMessageSource res = (ResourceBundleMessageSource) messageSource;
		res.addBasenames("com/gitee/ice1938/module/admin/sysoption/messages");
		String siteurl = optionService.findOption(OptionService.siteurl);
		if (siteurl == null) {
			optionService.initOption(OptionService.siteurl, "http://localhost:18060", "对外网访问网址",
			        "对外网访问网址eg: http://localhost:18060");
		}
	}

	@Bean("com_gitee_ice1938_module_admin_sysoption_initializer")
	public AbstractDataSourceInitializer moduleDataSourceInitializer(DataSource dataSource,
	        ResourceLoader resourceLoader) {
		return new AbstractBaseDataSourceInitializer(dataSource, resourceLoader) {
			@Override
			protected String getValidSql() {
				return "select * from sys_option";
			}

			@Override
			protected String getSchemaLocation() {
				return "classpath:db/sys_option_ddl.sql";
			}
		};
	}

	@Bean
	@ConditionalOnClass({ Caching.class, JCacheCacheManager.class })
	@ConditionalOnMissingBean(org.springframework.cache.CacheManager.class)
	public CacheManager cacheManager() {
		return new MissingJCacheCacheManager();
	}

}
